/*
 * osutil.c
 *
 *  Created on: 2012/09/07
 *      Author: softwareDeveloper
 */
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
#include "typedef.h"
#include "os.h"

#define MAX_OPTS (128)

static char* segs[MAX_OPTS];
static char* makestring(char* head, char* tail);

char** cmd_getsegs(char* s)
{
	assert(s != NULL);

	if (s == NULL || *s == '\0')
	{
		return NULL;
	}

	int index = 0;
	int flag  = FALSE;
	char* head = NULL;
	while(TRUE)
	{
		if (isspace(*s))
		{
			if (flag == TRUE)
			{
				segs[index++] = makestring(head, s);
				flag = FALSE;
			}
		}
		else if (*s == '\0' && flag == TRUE)
		{
			segs[index++] = makestring(head, s);
			break;
		}
		else
		{
			if (flag == FALSE)
			{
				head = s;
				flag = TRUE;
			}
		}

		s++;
	}

	char** p = (char**)malloc(index * sizeof(char*));
	for (int i = 0; i < index; i++)
	{
		p[i] = segs[i];
	}

	p[index] = NULL;

	return p;
}

void cmd_free(char** p)
{
	assert(p != NULL);

	for (int i = 0; p[i] != NULL; i++)
	{
		free(p[i]);
	}

	free(p);
}

static char* makestring(char* head, char* tail)
{
	assert(tail > head);

	char* str = (char*)malloc(tail - head + 1);
	char* p = str;
	while(head < tail)
	{
		*p++ = *head++;
	}

	*p = '\0';

	return str;
}

